package com.lndsnx.quick;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author: lndsnx
 * @date: 2025/7/15 22:53
 * @Version: 1.0
 * @description:
 */
public class Consumer {

    public static void main(String[] args) throws InterruptedException, MQClientException {

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("default_group");
        consumer.setNamesrvAddr("10.0.0.53:9876");
        // 从哪开始消费
        // CONSUME_FROM_LAST_OFFSET 上次消费的地方
        // CONSUME_FROM_FIRST_OFFSET 从头开始消费
        // CONSUME_FROM_TIMESTAMP 从指定时间开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        // CONSUME_FROM_TIMESTAMP 需要配置指定时间
        // consumer.setConsumeTimestamp("20230715231300");
        consumer.subscribe("TopicTest", "*");

        // 推模式
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                msgs.forEach(messageExt -> {
                    try {

                        System.out.println("收到消息:"+new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET));
                        System.out.println("消息Key:"+messageExt.getKeys());
                    } catch (UnsupportedEncodingException e) {
                        // 如果报错，则消费失败
                        e.printStackTrace();
                    }
                });
                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                // 成功，根据这个判断消费成功与否
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                // 失败
                // return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });
        consumer.start();

        System.out.printf("Consumer Started.%n");
    }
}
